﻿using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;

namespace WinPathMan
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            appPath = $"{Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)}\\heroius\\WinPathMan\\";
            Directory.CreateDirectory(appPath);

            PathContext = new OperationContext();
            DataContext = PathContext;
        }

        string appPath;
        public OperationContext PathContext { get; set; }

        private void LoadSys_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("执行加载将清空界面中的以编辑内容", "警告", MessageBoxButton.OKCancel, MessageBoxImage.Warning) == MessageBoxResult.OK)
            {
                PathContext.SystemPath.Clear();
                var paths = Utility.GetPaths(EnvironmentVariableTarget.Machine);
                foreach (var p in paths)
                {
                    PathContext.SystemPath.Add(p);
                }
            }
        }

        private void SaveSys_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("写入变量将影响系统功能，操作不可撤销", "警告", MessageBoxButton.OKCancel, MessageBoxImage.Warning) == MessageBoxResult.OK)
            {
                Backup(EnvironmentVariableTarget.Machine);
                Utility.SetPaths(PathContext.SystemPath.Select(entity => entity.Path), EnvironmentVariableTarget.Machine);
            }
        }

        private void LoadUser_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("执行加载将清空界面中的以编辑内容", "警告", MessageBoxButton.OKCancel, MessageBoxImage.Warning) == MessageBoxResult.OK)
            {
                PathContext.UserPath.Clear();
                var paths = Utility.GetPaths(EnvironmentVariableTarget.User);
                foreach (var p in paths)
                {
                    PathContext.UserPath.Add(p);
                }
            }
        }

        private void SaveUser_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("写入变量将影响系统功能，操作不可撤销", "警告", MessageBoxButton.OKCancel, MessageBoxImage.Warning) == MessageBoxResult.OK)
            {
                Backup(EnvironmentVariableTarget.User);
                Utility.SetPaths(PathContext.UserPath.Select(entity => entity.Path), EnvironmentVariableTarget.User);
            }
        }

        void Backup(EnvironmentVariableTarget tar)
        {
            var paths = Environment.GetEnvironmentVariable("Path", tar);
            string filename = $"{appPath}{DateTime.Now:yyyyMMddHHmmss}_{tar}.txt";
            using (StreamWriter writer = new StreamWriter(filename, false, Encoding.UTF8))
            {
                writer.Write(paths);
            }
        }
    }

}
